<?php
/**
 * description
 *
 * @category   Es和Db字段绑定关系
 * @package    PSR
 * @subpackage Documentation\API
 * @author     weiyizheng
 * @date       2022/11/9
 * @time       3:04 下午
 */

namespace Buu\Modules\EsStandard\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Http\Controllers\Controller;
use App\Models\DbInstance;
use App\Models\DbTables;
use App\Models\EsColumn;
use App\Models\EsColumnBindShip;
use App\Models\EsIndex;
use App\Models\EsSourceMapping;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class EsDbBindController extends Controller
{
	public function index(Request $request, Content $content, $id, $cid)
	{
		return $content
			->header('Es和Db绑定关系')
			->description(EsIndex::find($id)->name)
			->breadcrumb(
				['text' => 'Es字段列表', 'url' => '/EsStandard/es-column/' . $id],
				['text' => 'Es和Db绑定关系']
			)
			->body($this->grid($id, $cid));
	}

	protected function grid($id, $cid)
	{
		$grid = new Grid(new EsColumnBindShip());
		$grid->model()->where(['es_index_id' => $id, 'es_column_id' => $cid])->orderBy('id');
		$grid->disableFilter();
		$grid->disableExport();
		$grid->disableBatchActions();
		$grid->disableCreateButton();
		$grid->disablePagination();

		$grid->column('id', 'ID');
		$grid->column('es_column_id', 'es字段')->display(function () {
			return EsColumn::find($this->es_column_id)->column_name;
		});
		$grid->column('db_tables_id', '绑定数据表')->display(function () {
			return DbTables::find($this->db_tables_id)->table_name;
		});
		$grid->column('source_column_name', '绑定db字段');
		$grid->column('bind_type', '绑定类型')->using([0 => '等价', 1 => '映射'])->label([
			0 => 'success',
			1 => 'success'
		]);

		$grid->tools(function (Grid\Tools $tool) use ($id, $cid) {
			$tool->append(new UserButton(UserButton::TYPE_HREF, '', '新增绑定关系', '',
				url("/admin/EsStandard/es-db-bind/{$id}/{$cid}/add")));
		});
		return $grid;
	}

	public function add(Request $request, Content $content, $id, $cid)
	{
		$esIndex = EsIndex::find($id)->toArray();
		$esColumn = EsColumn::find($cid)->toArray();
		$sourceMapping = EsSourceMapping::where('es_index_id', $id)->distinct()->get('db_tables_id')->toArray();
		$dbTablesId = array_column($sourceMapping, 'db_tables_id');
		$form = new Form(new EsColumnBindShip());
		$form->footer(function (Form\Footer $footer) {
			$footer->disableEditingCheck();
			$footer->disableCreatingCheck();
			$footer->disableViewCheck();
		});
		$form->tools(function (Form\Tools $tools) use ($id) {
			$tools->disableList();
			$tools->disableDelete();
			$tools->disableView();
			$tools->append('<a href="/admin/EsStandard/es-column/' . $id .'" class="btn btn-sm btn-default" title="列表"><i class="fa fa-list"></i><span class="hidden-xs">&nbsp;列表</span></a>');
		});
		$form->html("<p><h5><b>{$esIndex['name']}</b></h5></p>", 'Es索引名')->disable()->setWidth(4, 2);
		$form->html("<p><h5><b>{$esColumn['column_name']}</b></h5></p>", 'Es字段')->disable()->setWidth(4, 2);
		$form->select('db_tables_id', '绑定db数据表')->options(
			DbTables::whereIn('id', $dbTablesId)->get()->pluck('table_name', 'id')
		)->load('source_column_name', '/admin/EsStandard/db-tables/getColumns')->required();
		$form->select('source_column_name', '绑定db字段')->options()->required();
		$form->select('bind_type', '绑定类型')->options(EsColumnBindShip::BIND_TYPE)->default(0)->required();

		$form->setAction("/admin/EsStandard/es-db-bind/{$id}/{$cid}/save");

		return $content
			->header('添加绑定')
			->description($esIndex['name'] . '--' . $esColumn['column_name'])
			->breadcrumb(
				['text' => '添加绑定']
			)
			->body($form);
	}

	public function edit(Request $request, Content $content, $id, $cid, $bid)
	{
		$esIndex = EsIndex::find($id)->toArray();
		$esColumn = EsColumn::find($cid)->toArray();
		$sourceMapping = EsSourceMapping::where('es_index_id', $id)->distinct()->get('db_tables_id')->toArray();
		$dbTablesId = array_column($sourceMapping, 'db_tables_id');
		$form = new Form(new EsColumnBindShip());
		$form->footer(function (Form\Footer $footer) {
			$footer->disableEditingCheck();
			$footer->disableCreatingCheck();
			$footer->disableViewCheck();
		});
		$form->tools(function (Form\Tools $tools) use ($id) {
			$tools->disableList();
			$tools->disableDelete();
			$tools->disableView();
			$tools->append('<a href="/admin/EsStandard/es-column/' . $id .'" class="btn btn-sm btn-default" title="列表"><i class="fa fa-list"></i><span class="hidden-xs">&nbsp;列表</span></a>');
		});
		$form->html("<p><h5><b>{$esIndex['name']}</b></h5></p>", 'Es索引名')->disable()->setWidth(4, 2);
		$form->html("<p><h5><b>{$esColumn['column_name']}</b></h5></p>", 'Es字段')->disable()->setWidth(4, 2);
		$form->select('db_tables_id', '绑定db数据表')->options(
			DbTables::whereIn('id', $dbTablesId)->get()->pluck('table_name', 'id')
		)->load('source_column_name', '/admin/EsStandard/db-tables/getColumns')->required();
		$form->select('source_column_name', '绑定db字段')->options(function () {
			if ($this->db_tables_id) {
				$dbTable = DbTables::find($this->db_tables_id)->toArray();
				return DbInstance::getColumnsById($dbTable['db_instance_id'], $dbTable['database'], $dbTable['tables'][0]);
			} else {
				return [];
			}
		})->required();
		$form->select('bind_type', '绑定类型')->options(EsColumnBindShip::BIND_TYPE)->default(0)->required();
		$form->hidden('es_column_name');
		$form->edit($bid);

		$form->hidden('es_bind_id')->value($bid);
		$form->setAction("/admin/EsStandard/es-db-bind/{$id}/{$cid}/save");

		return $content
			->header('编辑绑定')
			->description($esIndex['name'] . '--' . $esColumn['column_name'])
			->breadcrumb(
				['text' => '编辑绑定']
			)
			->body($form);
	}

	public function save(Request $request, $id, $cid)
	{
		$res = $request->all();

		$data = [
			'es_column_id' => $cid,
			'es_index_id' => $id,
			'db_tables_id' => $res['db_tables_id'] ?? 0,
			'source_column_name' => $res['source_column_name'] ?? '',
			'bind_type' => $res['bind_type'] ?? 0,
		];

		if (!empty($res['es_bind_id'])) {
			$msg = '编辑成功';
			// 编辑
			$data['update_time'] = time();
			$data['update_username'] = Admin::user()->username;

			EsColumnBindShip::where('id', $res['es_bind_id'])->update($data);
		} else {
			$msg = '添加成功';
			// 新增
			$data['add_username'] = Admin::user()->username;
			$data['update_username'] = Admin::user()->username;
			$data['add_time'] = time();
			$data['update_time'] = time();

			EsColumnBindShip::insert($data);
		}

		admin_toastr($msg, 'success', ['timeOut' => 3]);
		return redirect('/admin/EsStandard/es-column/' . $id);
	}

	public function delete($id, $cid, $bid)
	{
		if (!empty($bid)) {
			if (EsColumnBindShip::find($bid)->delete()) {
				return response()->json(['status' => true, 'message' => '成功']);
			} else {
				return response()->json(['status' => false, 'message' => '失败']);
			}
		} else {
			return response()->json(['status' => false, 'message' => '失败']);
		}
	}
}